package org.jeecg.modules.carLedger.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.backups.entity.Backups;
import org.jeecg.modules.backups.service.IBackupsService;
import org.jeecg.modules.carLedger.entity.LedgerExportVO;
import org.jeecg.modules.carLedger.service.ICarLedgerService;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Configuration
@EnableScheduling
@Slf4j
public class ExportScheduled {

    @Autowired
    private ICarLedgerService carLedgerService;//电子台账
    @Autowired
    private IBackupsService backupsService;

    @Scheduled(cron = "0 10 2 * * ?")//每天2点10分执行一次
    public void scheduledTasks() throws Exception{
        log.info("---------------开始执行备份----------------");
        Calendar calendar = Calendar.getInstance();// 获取当前时间
        calendar.add(Calendar.DAY_OF_MONTH, -1);// 将时间减去一天
        String s = DateUtils.formatDate(calendar);
        String filename = s + ".xlsx";
        List<LedgerExportVO> ledgers = carLedgerService.getBackups(s);
        try {
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(
                    s+"备份", "备份"), LedgerExportVO.class, ledgers);
            File savefile = new File("C:\\backups\\ygc");
            if (!savefile.exists()) {
                boolean mkDirs = savefile.mkdirs();
                if (!mkDirs){
                    throw new RuntimeException("创建文件夹失败");
                }
            }
            FileOutputStream fos = new FileOutputStream("C:\\backups\\ygc\\" + filename);
            workbook.write(fos);
            fos.close();

            // 获取文件大小并转换为KB
            Path filePath = Paths.get("C:\\backups\\ygc", filename);
            long fileSizeBytes = Files.size(filePath);
            int fileSizeKB = (int) (fileSizeBytes / 1024);

            Backups backups = new Backups();
            backups.setBackupsTime(new Date()).setFileName(filename).setFileUrl(filename).setFileSize(fileSizeKB).setStatus(1);
            backupsService.save(backups);

            log.info("---------------备份执行结束----------------");
            // 清理超过一个月的文件
            cleanOldFiles(savefile);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private void cleanOldFiles(File directory) {
        if (directory == null || !directory.exists() || !directory.isDirectory()) {
            log.warn("提供的路径不是有效的目录: {}", directory);
            return;
        }

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime cutoffTime = now.minusDays(30); // 计算30天前的时间点

        File[] files = directory.listFiles();
        if (files != null) {
            List<Backups> list = new ArrayList<>();
            for (File file : files) {
                LocalDateTime lastModifiedTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(file.lastModified()), ZoneId.systemDefault());
                if (lastModifiedTime.isBefore(cutoffTime)) {
                    if (!file.delete()) {
                        log.warn("无法删除文件: {}", file.getAbsolutePath());
                    } else {
                        log.info("已成功删除过期文件: {}", file.getAbsolutePath());
                        // 更新数据库中的记录状态
                        String fileName = file.getName();
                        Backups byFileName = backupsService.getByFileName(fileName);
                        byFileName.setStatus(0);
                        list.add(byFileName);
                        log.info("已将文件 {} 的状态更新为 0", fileName);
                    }
                }
            }
            backupsService.updateBatchById(list);
        } else {
            log.warn("没有找到任何文件需要清理.");
        }
    }

}
